package cn.yuanqiao.hengtaiOrganization.service.impl;

import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.archive.task.util.HttpClientUtil;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.service.RedisService;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.hengtaiOrganization.service.ISOrganizationService;
import cn.yuanqiao.system.domain.SysUserRole;
import cn.yuanqiao.system.mapper.SysUserMapper;
import cn.yuanqiao.system.mapper.SysUserRoleMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ProjectName: cn.yuanqiao.hengtaiOrganization.service.impl
 * @ClassName: ISOrganizationServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2025/3/31 10:35
 * @Version: 1.0
 **/
@Service
public class ISOrganizationServiceImpl implements ISOrganizationService {
    private final Logger logger = LoggerFactory.getLogger(ISOrganizationServiceImpl.class);
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Autowired
    private Environment environment;

    public void organizationList(String tenantCode, String beginTimeStamp) {
        logger.info("tenantCode：{}",tenantCode);
        String url = environment.getProperty("HTORG.url");
        if (org.apache.commons.lang3.StringUtils.isEmpty(url) || "null".equals(url)) {
            throw new SecurityException("url参数未配置！！！" + url);
        }
        String username = environment.getProperty("HTORG.user");
        if (StringUtils.isNULLString(username) || "null".equals(username)) {
            throw new SecurityException("username参数未配置！！！" + username);
        }
        String pass = environment.getProperty("HTORG.pass");
        if (StringUtils.isNULLString(pass) || "null".equals(pass)) {
            throw new SecurityException("password参数未配置！！！" + pass);
        }
        String roleId = environment.getProperty("HTORG.roleId");
        if (StringUtils.isNULLString(roleId) || "null".equals(roleId)) {
            throw new SecurityException("roleId参数未配置！！！" + roleId);
        }
        String deptId = environment.getProperty("HTORG.deptId");
        if (StringUtils.isNULLString(deptId) || "null".equals(deptId)) {
            throw new SecurityException("roleId参数未配置！！！" + deptId);
        }
        String encryption = environment.getProperty("encryption");
        if (StringUtils.isNULLString(encryption) || "null".equals(encryption)) {
            throw new SecurityException("encryption参数未配置！！！" + encryption);
        }
        String urlAddress = "/api/sys-organization/sysSynchroGetOrg/getUpdatedElementsByToken";
        Integer count = 100;
        int pageNo = 1;
        String token = null;
        while (count == 100) {
            Map<String, Object> mapRequest = new HashMap<>();
            mapRequest.put("pageNo", pageNo);
            mapRequest.put("count", 100);
            mapRequest.put("returnOrgType", "[{\"type\":\"person\"}]");
            // mapRequest.put("beginTimeStamp", beginTimeStamp);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(token)) {
                mapRequest.put("token", token);
            }
            logger.info("请求地址:{}  请求参数：{}", url + urlAddress, JSON.toJSONString(mapRequest));
            String msg = HttpClientUtil.doPostBasicAuthJson(url + urlAddress, JSON.toJSONString(mapRequest), username, pass);
            JSONObject resJson = JSONObject.parseObject(msg);
            count = resJson.getInteger("count");
            token = resJson.getString("token");
            logger.info("返回状态:{} 返回总数:{} 返回token: {}", resJson.getInteger("returnState"), count, token);
            if ("2".equals(resJson.getString("returnState"))) {
                JSONArray data = resJson.getJSONArray("message");
                logger.info("返回数据:{}{}", data, data.size());
                List<SysUserRole> urs = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    JSONObject object = (JSONObject) data.get(i);
                    if (object.get("isAvailable").equals(true)) {
                        SysUser sysUser = new SysUser();
                            Long id  =SnowflakeIdGenerator.generateId();
                        sysUser.setUserId(id);
                        if(!object.containsKey("id")) continue;
                        sysUser.setOneId(object.get("id").toString());
                        if(!object.containsKey("name")) continue;
                        sysUser.setNickName(object.get("name").toString());
                        if(!object.containsKey("loginName")) continue;
                        sysUser.setUserName(object.get("loginName").toString());
                        String  password = SecurityUtils.encryptPassword("123456", encryption);
                        sysUser.setPassword(password);
                        sysUser.setTenantCode(tenantCode);
                        sysUser.setDeptId(Long.valueOf(deptId));
                        sysUser.setPhonenumber(object.containsKey("mobileNo")?object.get("mobileNo").toString():" ");
                        sysUser.setEmail(object.containsKey("email")?object.get("email").toString():" ");
                        boolean b = addUser(sysUser);
                        if (b) {
                            SysUserRole ur = new SysUserRole();
                            ur.setUserId(sysUser.getUserId());
                            ur.setRoleId(Long.valueOf(roleId));
                            urs.add(ur);
                        }
                    }
                }
                if (urs != null && urs.size() > 0) {
                    logger.info("urs信息:{} 大小:{} 返回token: {}", JSON.toJSONString(urs), urs.size());
                    userRoleMapper.batchUserRole(urs);
                }
            }
            pageNo++;
        }

    }

    @Override
    public void syncTaskht(Map<String, Object> map) {

        String daxturl = environment.getProperty("HTORG.daxturl");
        if (StringUtils.isNULLString(daxturl) || "null".equals(daxturl)) {
            throw new SecurityException("domainOpenapi参数未配置！！！");
        }
        String url = environment.getProperty("HTORG.url");
        if (StringUtils.isNULLString(url) || "null".equals(url)) {
            throw new SecurityException("url参数未配置！！！");
        }
        String username = environment.getProperty("HTORG.user");
        if (StringUtils.isNULLString(username) || "null".equals(username)) {
            throw new SecurityException("username参数未配置！！！");
        }
        String password = environment.getProperty("HTORG.pass");
        if (StringUtils.isNULLString(password) || "null".equals(password)) {
            throw new SecurityException("password参数未配置！！！");
        }

        String pType = String.valueOf(map.get("pType"));
        String tenantCode = String.valueOf(map.get("tenantId"));
        String taskId = (String) map.get("taskId");
        String processInstanceId = (String) map.get("processInstanceId");
        String taskDefinitionKey = (String) map.get("taskDefinitionKey");
        String definitionKey = (String) map.get("definitionKey");
        //流程名称
        String processName = (String) map.get("processName");
        //节点名称
        String taskName = (String) map.get("taskName");
        //发起人名称
        String startUserId = (String) map.get("startUserId");
        String urlAddress = "/sendTodo";
        String assignee = (String) map.get("assignee");
        logger.info("审批人名字:{} 请求参数：{}", assignee, JSON.toJSONString(map));
        SysUser assigneeUserInfo = sysUserMapper.checkUserNameUnique(assignee, tenantCode);
        Map<String, Object> userList = new HashMap<>();
        userList.put("LoginName", assigneeUserInfo.getUserName());
        Map<String, Object> mapRequest = new HashMap<>();
        mapRequest.put("appName", "档案管理系统");
        mapRequest.put("modelName", "档案管理系统个人事务");
        mapRequest.put("modelId", taskId);
        mapRequest.put("targets", JSON.toJSONString(userList));
        if ("DS".equals(pType) || map.containsKey("PROCESS_STARTED")) {
            urlAddress = "/api/sys-notify/sysNotifyTodoRestService/sendTodo";
            mapRequest.put("subject", taskName);
            mapRequest.put("type", 1);
            mapRequest.put("optType", 1);
            mapRequest.put("createTime", DateUtils.getTime());
            //对参数进行base64编码
            String str = "taskId=" + taskId + "&assignee=" + assigneeUserInfo.getUserId() + "&createTime=" + DateUtils.dateTime();
            String base64Str = Base64.getEncoder().encodeToString(str.getBytes());
            String mobileUrlf = daxturl + "/task/task?secret=" + base64Str;
            mapRequest.put("link", mobileUrlf);
            mapRequest.put("mobileLink", mobileUrlf);
            mapRequest.put("padLink", mobileUrlf);
        } else if ("YS".equals(pType)) {
            urlAddress = "/api/sys-notify/sysNotifyTodoRestService/setTodoDone";
            mapRequest.put("optType", 2);
        }
        logger.info("请求地址:{} 请求参数：{}", url + urlAddress, JSON.toJSONString(mapRequest));
        String msg = HttpClientUtil.doPostBasicAuthJson(url + urlAddress, JSON.toJSONString(mapRequest), username, password);
        JSONObject resJson = JSONObject.parseObject(msg);
        logger.info("返回参数:{}", resJson);
        if ("2".equals(resJson.getString("returnState"))) {
            logger.info("待办新增发送成功！！！");
        } else {
            logger.info("待办新增发送失败！！！");
            logger.error("错误信息-->[{}]", resJson.getString("message"));
        }
    }

    public static void main(String[] args) {
        //  String str = "taskId=15034&assignee=340728011190046720&createTime=" + DateUtils.dateTime();

        String str = "dbfw:Dbfw@2023";
        String base64Str = Base64.getEncoder().encodeToString(str.getBytes());
        String mobileUrlf = "http://localhost/task/task?secret=" + base64Str;
        System.out.println(mobileUrlf);
    }

    private boolean addUser(SysUser sysUser) {
        SysUser quertSysUser = new SysUser();
        quertSysUser.setOneId(sysUser.getOneId());
        List<SysUser> sysUsers = sysUserMapper.selectUserList(quertSysUser);
        if (sysUsers != null && sysUsers.size() > 0) {
            logger.info("修改用户:{}", sysUsers);
            sysUserMapper.updateUserByOneId(sysUser);
            return  false;
        } else {
            logger.info("新增用户:{}", sysUsers);
            sysUserMapper.insertUser(sysUser);
            return true;
        }
    }


//    public List<Map<String, Object>> getOneIdsArray(Map<String, Object> map,String tenantCode,String taskDefinitionKey) {
//        //获取当前节点配置 是 表达式还是角色还是具体人
//        String processDefinitionId = (String) map.get("processDefinitionId");
//        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
//        Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
//        //遍历节点
//        List< Map<String, Object>> oneIds = new ArrayList<>();
//        for (FlowElement e : flowElements) {
//            String str = "";
//            String currentKey = taskDefinitionKey;
//            if (StringUtils.isNotEmpty(currentKey)) {
//                //获得当前节点
//                if (e.getId().equals(currentKey)) {
//                    if (e instanceof UserTask) {
//                        String assignee = ((UserTask) e).getAssignee();
//                        List<String> candidateGroups = ((UserTask) e).getCandidateGroups();
//                        List<String> candidateUsers = ((UserTask) e).getCandidateUsers();
//                        if (candidateUsers != null && candidateUsers.size() != 0) {
//                            for (String s : candidateUsers) {
//                                if ("${authService.deptLeader()}".equals(s)) {
//                                    str = String.valueOf(map.get("deptLeader"));
//                                } else if ("${authService.archiveDeptLeader()}".equals(s)) {
//                                    str = String.valueOf(map.get("archiveDeptLeader"));
//                                } else if ("${authService.deptDagly()}".equals(s)) {
//                                    str = String.valueOf(map.get("deptDagly"));
//                                }
//                                com.alibaba.fastjson2.JSONArray jsonArray = com.alibaba.fastjson2.JSONArray.parseArray(str);
//                                for (int i = 0; i < jsonArray.size(); i++) {
//                                    Map<String, Object> userList = new HashMap<>();
//                                    String uname = String.valueOf(jsonArray.get(i));
//                                    SysUser assigneeUserInfo = sysUserMapper.checkUserNameUnique(uname, tenantCode);
//                                    String pToUserId = assigneeUserInfo == null ? "" : assigneeUserInfo.getOneId();
//                                    userList.put("id",pToUserId);
//                                    oneIds.add(userList);
//                                }
//                            }
//                            if (assignee != null && !"null".equalsIgnoreCase(assignee)) {
//                                Map<String, Object> userList = new HashMap<>();
//                                SysUser assigneeUserInfo = sysUserMapper.checkUserNameUnique(assignee, tenantCode);
//                                String pToUserId = assigneeUserInfo == null ? "" : assigneeUserInfo.getOneId();
//                                userList.put("id",pToUserId);
//                                oneIds.add(userList);
//
//                            }
//                            if (candidateGroups != null && candidateGroups.size() != 0) {
//                                String string = candidateGroups.stream().collect(Collectors.joining("','"));
//                                List<Map<String, Object>> maps = yqdaarticulatedMapper.executeSql("select one_id from sys_user where user_id in (select user_id from sys_user_role" +
//                                        " where role_id = (select role_id from sys_role where role_key in( '" + string + "')))");
//                                for (int i = 0; i < maps.size(); i++) {
//                                    Map<String, Object> userList = new HashMap<>();
//                                    Map<String, Object> map1 = maps.get(i);
//                                    if (map1 != null) {
//                                        userList.put("id",String.valueOf(map1.get("ONE_ID")));
//                                        oneIds.add(userList);
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        return oneIds;
//    }


}
